package com.lry.pda.bottom.c.backend;

import java.util.Map;

public class DirectMemValueSetter implements IValueSetter {
    private int memAddr = 0;
    private int byteSize = 0;

    public DirectMemValueSetter(int memAddr,int byteSize) {
        this.memAddr = memAddr;
        this.byteSize = byteSize;
    }

    @Override
    public void setValue(Object obj)   {
        MemoryHeap memHeap = MemoryHeap.getSelf();
        Map.Entry<Integer, byte[]> entry = memHeap.getMem(memAddr);
        byte[] content = entry.getValue();
        int offset = memAddr - entry.getKey();
        Integer i = (Integer)obj;
        try {
            if (byteSize == 4) {
                content[offset] = (byte)((i>>24) & 0xFF);
                content[offset + 1] = (byte)((i>>16) & 0xFF);
                content[offset + 2] = (byte)((i>>8) & 0xFF);
                content[offset + 3] = (byte)(i & 0xFF);
            } else {
                content[offset] = (byte)(i & 0xFF);
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
            System.exit(1);
        }
    }

}